<template>
  <view class="wallet-page">
    <!-- 顶部背景 -->
    <view class="wallet-header">
      <image class="header-bg" src="/static/Images/wallet/Toubu.png" mode="widthFix"></image>
      <view class="header-content">
        <view class="back-btn" @click="navigateBack">
          <img class="iconfont icon-left" src="/static/Images/wallet/Fanhuibai.png" alt="">
        </view>
        <view class="title">我的佣金</view>
      </view>
    </view>
    
    <!-- 佣金卡片 -->
    <view class="wallet-card">
      <view class="card-status">账户资金保障中</view>
      
      <view class="card-amount-label">可提现佣金（元）</view>
      <view class="card-amount">{{ displayBalance }}</view>
      
      <button class="withdraw-btn" @click="handleWithdraw">提现</button>
    </view>
    
    <!-- 佣金记录标签 -->
    <view class="record-tabs">
      <view class="tab" :class="{active: activeTab === 'detail'}" @click="switchTab('detail')">收益明细</view>
      <view class="tab" :class="{active: activeTab === 'record'}" @click="switchTab('record')">提现明细</view>
      <view class="date-filter" @click="showDatePicker">
        <image class="date-icon" src="/static/Images/wallet/Time.png" mode="aspectFit"></image>
        <text class="date-text">日期</text>
      </view>
    </view>
    
    <!-- 佣金记录列表（动态渲染+滚动分页） -->
    <view class="record-section">
      <scroll-view class="record-scroll" scroll-y="true" @scrolltolower="onScrollToLower" :style="{ height: scrollHeight }">
        <view class="record-list">
          <view class="record-item" v-for="(item, idx) in records" :key="item.id || idx">
            <view class="record-left">
              <view class="record-title">
                {{ activeTab === 'detail' ? (item.desc || item.text_type || '收益') : '提现申请' }}
              </view>
              <view class="record-subtitle" v-if="activeTab === 'detail'">
                变动后：¥{{ item.after_money }}
              </view>
              <view class="record-subtitle" v-else>
                {{ getWithdrawStatus(item.status) }} | 手续费：¥{{ item.fee || '0.00' }}
              </view>
              <view class="record-time">{{ item.create_time }}</view>
            </view>
            <view class="record-amount" :class="activeTab === 'detail' && isIncome(item) ? 'positive' : 'negative'">
              {{ activeTab === 'detail' && isIncome(item) ? '+' : '-' }}¥{{ item.money }}
            </view>
          </view>

          <view v-if="loading" class="loading">加载中...</view>
          <view v-if="!loading && records.length === 0" class="empty">暂无记录</view>
          <view v-if="!hasMore && records.length > 0" class="no-more">没有更多数据</view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 底部指示器 -->
    <view class="bottom-indicator"></view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { userApi } from '@/utils/api'
import { setStorage, STORAGE_KEYS } from '@/utils/storage'

// 当前激活的标签（detail: 收益 type=1；record: 提现 type=2）
const activeTab = ref('detail')

// 顶部余额（可提现佣金）与用户重要字段
const balance = ref(0)
const realName = ref('')
const alipayAccount = ref('')
const displayBalance = computed(() => {
  const n = Number(balance.value)
  return Number.isFinite(n) ? n.toFixed(2) : '0.00'
})

// 列表与分页状态
const records = ref([])
const page = ref(1)
const size = ref(10)
const hasMore = ref(true)
const loading = ref(false)
// 设定滚动区域高度，避免页面整体滚动导致 scrolltolower 不触发
const scrollHeight = ref('calc(100vh - 520rpx)')

// 切换标签
const switchTab = (tab) => {
  if (activeTab.value === tab) return
  activeTab.value = tab
  resetAndFetch()
}

const resetAndFetch = () => {
  page.value = 1
  hasMore.value = true
  records.value = []
  fetchList(true)
}

// 判断是否收入（type=1收入；type=2提现）
const isIncome = (item) => Number(item?.type) === 1

// 获取提现状态文本
const getWithdrawStatus = (status) => {
  switch (Number(status)) {
    case 1:
      return '待审核'
    case 2:
      return '已通过'
    case 0:
      return '已拒绝'
    default:
      return '未知状态'
  }
}

// 加载列表
const fetchList = async (reset = false) => {
  if (loading.value || !hasMore.value) return
  loading.value = true
  try {
    let res
    if (activeTab.value === 'detail') {
      // 收益明细 - 调用原有接口
      res = await userApi.getUserAccountLog(page.value, size.value)
      const rawList = Array.isArray(res?.data) ? res.data : (Array.isArray(res?.data?.list) ? res.data.list : [])
      // 过滤收益类型 (type=1)
      const filtered = rawList.filter(it => Number(it.type) === 1)
      records.value = records.value.concat(filtered)
      
      if (!rawList.length || rawList.length < size.value) {
        hasMore.value = false
      } else {
        page.value += 1
      }
    } else {
      // 提现明细 - 调用getWithdrawLog接口
      res = await userApi.getWithdrawLog(page.value, size.value)
      const data = res?.data || {}
      const rawList = Array.isArray(data.list) ? data.list : []
      
      // 提现记录不需要过滤，直接显示所有记录
      records.value = records.value.concat(rawList)
      
      if (!rawList.length || rawList.length < size.value) {
        hasMore.value = false
      } else {
        page.value += 1
      }
    }
  } catch (e) {
    console.error('获取佣金记录失败:', e)
    uni.showToast({ title: e.message || '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 获取用户信息以渲染可提现佣金（balance）并保存 real_name / alipay
const fetchUserInfo = async () => {
  try {
    const response = await userApi.getUserInfo()
    const data = (response && (response.data?.data ?? response.data ?? response)) || {}
    const val = data?.balance ?? 0
    balance.value = Number(val) || 0
    realName.value = data?.real_name || ''
    alipayAccount.value = data?.alipay || ''
  } catch (err) {
    console.error('获取用户信息失败:', err)
  }
}

// 滚动触底
const onScrollToLower = () => {
  fetchList()
}

// 返回上一页
const navigateBack = () => {
  uni.navigateBack()
}

// 处理提现
const handleWithdraw = async () => {
  // 确保有最新用户信息（可选）
  // await fetchUserInfo()

  if (!realName.value) {
    uni.showModal({
      title: '提示',
      content: '未实名认证，无法提现。是否前往实名认证？',
      confirmText: '去认证',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/realname/index' })
        }
      }
    })
    return
  }

  if (!alipayAccount.value) {
    uni.showModal({
      title: '提示',
      content: '未捆绑提现账号，无法提现。是否前往绑定提现账号？',
      confirmText: '去绑定',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/wallet/account?method=alipay' })
        }
      }
    })
    return
  }

  // 隐式透传余额与支付宝账号到提现页（本地存储，不在 URL 显示）
  const b = Number(balance.value) || 0
  setStorage(STORAGE_KEYS.WITHDRAW_BALANCE, b)
  setStorage(STORAGE_KEYS.WITHDRAW_ALIPAY, alipayAccount.value)
  uni.navigateTo({ url: '/pages/wallet/withdraw' })
}

// 显示日期选择器
const showDatePicker = () => {
  uni.showToast({
    title: '日期筛选功能开发中',
    icon: 'none'
  })
}

onMounted(() => {
  fetchUserInfo()
  fetchList(true)
})
</script>

<style lang="scss">
.wallet-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 顶部背景 */
.wallet-header {
  position: relative;
  width: 100%;
  height: 200rpx;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.header-content {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  padding-top: 80rpx;
  padding-left: 30rpx;
}

.back-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-left {
  font-size: 20rpx;
  color: #fff;
  width: 1.5rem;
  height: 1.5rem;
}

.title {
    color: #fff;
  font-size: 36rpx;
  font-weight: 500;
  flex: 1;
  text-align: center;
  margin-right: 60rpx; /* 为了平衡左侧返回按钮的宽度 */
}

/* 佣金卡片 */
.wallet-card {
  margin: -40rpx 30rpx 0;
  padding: 30rpx;
  position: relative;
  z-index: 3;
  margin-top: 2.25rem;
}

.card-status {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.card-amount-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.card-amount {
  font-size: 80rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.withdraw-btn {
  background-color: #ff4d4f;
  color: #fff;
  border-radius: 100rpx;
  font-size: 32rpx;
  height: 80rpx;
  line-height: 80rpx;
  border: none;
}

/* 记录标签 */
.record-tabs {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin-top: 30rpx;
  position: relative;
}

.tab {
  font-size: 30rpx;
  color: #666;
  margin-right: 40rpx;
  position: relative;
  padding-bottom: 10rpx;
}

.tab.active {
  color: #ff4d4f;
  font-weight: 500;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 4rpx;
  background-color: #ff4d4f;
  border-radius: 2rpx;
}

.date-filter {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.date-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.date-text {
  font-size: 28rpx;
  color: #666;
}

/* 记录列表容器与滚动 */
.record-section {
  background-color: #fff;
}
.record-scroll {
  width: 100%;
}
.record-list {
  background-color: #fff;
  padding: 0 30rpx;
}

.record-item {
  display: flex;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #eee;
}

.record-left {
  flex: 1;
}

.record-title {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.record-subtitle {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.record-time {
  font-size: 24rpx;
  color: #999;
}

.record-amount {
  font-size: 36rpx;
  font-weight: 500;
  align-self: center;
}

.positive {
  color: #52c41a; /* 收入用正向绿色 */
}

.negative {
  color: #ff4d4f; /* 支出用红色 */
}

.loading, .empty, .no-more {
  text-align: center;
  padding: 20rpx 0 30rpx;
  color: #999;
  font-size: 26rpx;
}

/* 底部指示器 */
.bottom-indicator {
  width: 120rpx;
  height: 8rpx;
  background-color: #ddd;
  border-radius: 4rpx;
  margin: 30rpx auto;
}
</style>